package com.leyou.gateway.filter;

import com.leyou.common.constants.JwtConstants;
import com.leyou.common.exceptions.LyException;
import com.leyou.pojo.dto.Payload;
import com.leyou.pojo.util.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpCookie;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
@Component
@Slf4j
public class RefreshRedisFilter implements GlobalFilter {
    @Autowired
    private JwtUtils jwtUtils;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        try {
            //获取cookie
            ServerHttpRequest request = exchange.getRequest();
            MultiValueMap<String, HttpCookie> cookies = request.getCookies();
            HttpCookie cookie = cookies.getFirst(JwtConstants.COOKIE_NAME);
            //解析cookie，并判断redis是否有效
            if(cookie==null){
                log.info("用户还未登录");
                //如果用户未登录，直接放行
                return chain.filter(exchange);
            }
            String jwt = cookie.getValue();
            Payload payload = jwtUtils.parseJwtAndRedis(jwt);
            //刷新
            jwtUtils.refreshRedis(payload.getUserDetail().getId());
        } catch (Exception e) {
            log.error("刷新token失败");
        }
        //刷新时间
        return chain.filter(exchange);
    }
}
